import requests
import json

def main():
    # 1.创建会话
    url = "https://qianfan.baidubce.com/v2/app/conversation"
    
    payload = json.dumps({
        "app_id": "d299fb25-c98c-40e6-ac0c-74af300ed0b1"
    })
    headers = {
        'Content-Type': 'application/json',
        'X-Appbuilder-Authorization': 'Bearer bce-v3/ALTAK-dqem39HTQN4Ri2TUQyaJv/ea2484e9a7c5128d727917e6375462920a84c169'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    conversation_id = json.loads(response.text)['conversation_id']

    # 2.问答    
    url = "https://qianfan.baidubce.com/v2/app/conversation/runs"
    
    # 获取键盘输入
    user_input = input("请输入你的问题：")

    payload = json.dumps({
        "app_id": "d299fb25-c98c-40e6-ac0c-74af300ed0b1",
        "query": user_input,
        "stream": False,
        "conversation_id": conversation_id  # 使用之前获取的conversation_id
    })
    headers = {
        'Content-Type': 'application/json',
        'X-Appbuilder-Authorization': 'Bearer bce-v3/ALTAK-dqem39HTQN4Ri2TUQyaJv/ea2484e9a7c5128d727917e6375462920a84c169'
    }
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    # 3.只打印answer
    # 解析JSON字符串
    response_data = json.loads(response.text)
    # 提取answer字段
    answer = response_data.get('answer', '未找到答案')  # 如果answer不存在，则默认为'未找到答案'
    print(answer)
    # 将answer保存到txt文件中
    with open('answer.txt', 'w', encoding='utf-8') as file:
        file.write(answer)

    print("答案已保存到answer.txt文件中")

if __name__ == "__main__":
    main()